//
//  TBDetailView.swift
//  LeGou
//
//  Created by lxm on 2022/8/8.
//

import UIKit
import RxSwift

class TBDetailView: UIView {

    //MARK: --------------------属性--------------------
    var dataSorce = [String]()
    
    var disposeBag = DisposeBag()
    //MARK: --------------------UI控件--------------------
    var loading = XMLoadingView()
    
    var stack = ZMUtil.stackView(axis: .vertical, spacing: 0)
    //MARK: --------------------生命周期--------------------
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUI()
        bindAction()
        addConstraints()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        setUI()
        bindAction()
        addConstraints()
    }

    //MARK: --------------------UI--------------------
    func setUI() {
        
    }
    
    func addConstraints() {
     
    }
    
    //MARK: --------------------methods--------------------
    func bindAction() {
        
    }
    
    
    func imageDownLoadTask(url : String) -> Observable<UIImage?> {
        let ob = Observable<UIImage?>.create { (ob) -> Disposable in
            guard let imgUrl = URL.init(string: url) else {
                ob.onNext(nil)
                ob.onCompleted()
                let dis = Disposables.create {
                    
                }
                return dis
            }
            
            var task : DownloadTask?
            if KingfisherManager.shared.cache.diskStorage.isCached(forKey: url) == false{
                task = KingfisherManager.shared.downloader.downloadImage(with: imgUrl, options: []) { r in
                    switch r {
                    case .success(let img):
                        KingfisherManager.shared.cache.store(img.image, forKey: url)
                        ob.onNext(img.image)
                        ob.onCompleted()
                        XMLogger.info("缓存图片成功----\(url))")
                    case .failure(let _):
                        ob.onNext(nil)
                        ob.onCompleted()
                        XMLogger.error("缓存载图片失败----\(url)")
                    }
                }
            } else {
                if let data = try? KingfisherManager.shared.cache.diskStorage.value(forKey: url), let img = UIImage.init(data: data) {
                    ob.onNext(img)
                    ob.onCompleted()
                } else {
                    ob.onNext(nil)
                    ob.onCompleted()
                }
                XMLogger.info("已经缓存----\(url))")
            }
            
            let dis = Disposables.create {
                if let task = task {
                    task.cancel()
                }
            }
            return dis
        }
        return ob
    }
    
    func loadImages(dataSorce : [String]) {
        stack.arrangedSubviews.forEach {[weak stack] v in
            guard let stack = stack else {return}
            stack.removeArrangedSubview(v)
        }
        self.dataSorce = dataSorce.map({ val in
            if val.contains("http") {
                return val
            } else {
                return "http:" + val
            }
        })
        var array = [Observable<UIImage?>]()
        for url in self.dataSorce {
            let task = imageDownLoadTask(url: url)
            array.append(task)
        }
        loading.showInView(fatherView: self)
        Observable.combineLatest(array).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            for img in resp {
                let imageView = ZMUtil.imageView(image: img)
//                imageView.layer.cornerRadius = 8
//                imageView.clipsToBounds = true
                stack.addArrangedSubview(imageView)
                if let img = img {
                    let width = zm.width
                    let height = img.size.height / img.size.width * width
                    imageView.snp.makeConstraints { make in
                        make.height.equalTo(height)
                        make.width.equalTo(width)
                    }
                }
            }
            addSubview(stack)
            stack.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
        }).disposed(by: disposeBag)
    }
    
    //MARK: --------------------delegate--------------------

}
